package com.lyf.core.rx;

import android.text.TextUtils;

import com.blankj.utilcode.util.StringUtils;
import com.google.gson.JsonSyntaxException;
import com.lyf.core.R;
import com.lyf.core.common.CoreLibrary;
import com.lyf.core.common.RxSubscriberExceptionHanlder;
import com.lyf.core.presenter.view.BaseView;

import java.net.ConnectException;

import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import okhttp3.ResponseBody;
import retrofit2.HttpException;


public abstract class BaseSubscriber<T> implements Observer<T> {

    protected BaseView baseView;
    protected RxSubscriberExceptionHanlder exceptionHanlder;

    public BaseSubscriber(BaseView baseView) {
        this.baseView = baseView;
        exceptionHanlder= CoreLibrary.getInstance().getRxSubscriberExceptionHanlder();
    }

    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onError(Throwable e) {
        baseView.stopLoading();
        /**
         * 返回数据中的code 200以外的业务在BaseException处理
         */
        if (e instanceof BaseException) {
            BaseException baseException = (BaseException) e;
            if (!TextUtils.isEmpty(baseException.msg)) {
                baseView.showMessage(baseException.msg);
            }
            apiException(baseException.code);
        } else if (e instanceof JsonSyntaxException) {
            baseView.showMessage(StringUtils.getString(R.string.http_data_erron));
        } else if (e instanceof ConnectException) {
            baseView.showMessage(StringUtils.getString(R.string.http_erron));
        } else if (e instanceof NullPointerException) {

        } else if (e instanceof HttpException){
            try {
                ResponseBody body = ((HttpException) e).response().errorBody();
                String res = body.string();
                if (!TextUtils.isEmpty(res)){
                    if (res.equals("请求未授权")){
                        if (exceptionHanlder!=null){
                            exceptionHanlder.loginExpired();
                        }
                    }
                    apiException(res);
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        }else if (!TextUtils.isEmpty(e.getMessage())) {
            baseView.showMessage(e.getMessage());
        }  else {
            baseView.showMessage(StringUtils.getString(R.string.http_erron));
        }
    }

    @Override
    public void onComplete() {
        baseView.stopLoading();
    }

    public void apiException(int code){

    }
    public void apiException(String msg){

    }

}
